/**
 * 处理首页以及活动页的数据
 */
import axios from "axios";
import store from "@/store";
import getpageName from "../gw/getPageName"

//任务队列
let tasks = [];
let dataStore;
let pageName= getpageName()
export const baseComponentNames = {
	GuessYouLike: {},//猜你喜欢组件
	HomeCarousel: {},//轮播
	NewZone: {},//横幅图片
	UserCard: {},//扫一扫会员卡
	HomeNotice: {},//公告
	ProductItemNew: {},//十格图片
	FeaturedGoodsNew: {},//五宫格图片
	FirstClassifyNew: {},//楼层导航
	activitiesTwoPro: {},//两列下滑
	activitiesNinePro: {},//三列下滑
	activitiesThreePic: {},//三列横滑
	activitiesOnePro: {},//单列下滑
	activitiesbanner: {},//活动页顶部大海报
	activitiesSlidePic: {},//下滑图片模块
	ActivitieCoupons: {},//固定优惠券
	ActivitieCoupons2: {},//自定义优惠券
	TabHead: {},//Tab导航组件
	PointMallCarousel:{},
	GiftBuyCarousel:{},
}
//清除内存中的dataStore
export function clearDataStoreForMemory() {
	// console.log("handleData--->清空操作")
	dataStore = {};
	tasks = [];
}

//不同页面不同的初始化dataStore策略
const initMethods = (pageName = getpageName()) => {
	let _methods = {
		home: () => {
            dataStore = sessionStorage.getItem('dataStore');
            let exits = false;//缓存的数据是否存在
            if (!dataStore) {
                dataStore = {
                    ...baseComponentNames
                }
            } else {
				exits = true;
				try {
					dataStore = JSON.parse(dataStore);
					// console.log(dataStore);
				} catch (err) {
					console.log("解析json字符串出错", err)
				}
            }
            return Promise.resolve({
                exits
            });
        },
		NewThematicActivities: async () => {
			if(window.localforage){
				dataStore = await window.localforage.getItem(pageName);
			}
			console.log("打印dataStore",dataStore)
            // dataStore = window.localStorage.getItem(pageName);
            let exits = false;//缓存的数据是否存在
            //没有dataStore并且没有对应页面的dataStore，需要请求数据，存到localforage(indexeddb)中
            if (!dataStore || !window.localforage) {
				// debugger
                dataStore = {
                    ...baseComponentNames
                }
            } else {
                exits = true;
			}
			console.log("exits",exits)
            return Promise.resolve({
                exits
            });
		},
		buyGiftCard: async () => {
            dataStore = await window.localforage.getItem(pageName);
            let exits = false;//缓存的数据是否存在
            //没有dataStore并且没有对应页面的dataStore，需要请求数据，存到localforage(indexeddb)中
            if (!dataStore) {
                dataStore = {
                    ...baseComponentNames
                }
            } else {
                exits = true;
            }
            return Promise.resolve({
                exits
            });
		},
		IntegralBuy: async () => {
            dataStore = await window.localforage.getItem(pageName);
            // dataStore = window.localStorage.getItem(pageName);
            let exits = false;//缓存的数据是否存在
            //没有dataStore并且没有对应页面的dataStore，需要请求数据，存到localforage(indexeddb)中
            if (!dataStore) {
				// debugger
                dataStore = {
                    ...baseComponentNames
                }
            } else {
                exits = true;
            }
            return Promise.resolve({
                exits
            });
		},
		
	}
	return _methods[pageName] || _methods.NewThematicActivities;
}

//不同页面不同的存储缓存策略
const saveMethods = (pageName = getpageName()) => {
    let _methods = {
		home: () => {
			try {
				console.log("存储进sessionStorage的数据", dataStore);
            	sessionStorage.setItem("dataStore", JSON.stringify(dataStore));
			} catch (err) {
				console.log("存储进sessionStorage的数据出错", err);
			}
			
        },
		NewThematicActivities: () => {
            console.log("要存进localforage的数据", dataStore);
            // window.localStorage.setItem(pageName, JSON.stringify(dataStore));
            window.localforage.setItem(pageName, dataStore).then(data => console.log("存储完毕", data));
		},
		buyGiftCard: () => {
			console.log("要存进localforage的数据", dataStore);
            window.localforage.setItem(pageName, dataStore).then(data => console.log("存储完毕", data));
		},
		IntegralBuy: () => {
            console.log("要存进localforage的数据", dataStore);
            window.localforage.setItem(pageName, dataStore).then(data => console.log("存储完毕", data));
		},
		
    }
    return _methods[pageName] || _methods.NewThematicActivities;
}

/**
 * 初始化数据
 * @param {*} isRefresh 用来标志是否要强制刷新
 * @param {*} componentObj 代表更新哪个组件的数据
 */
async function initData(isRefresh = false, componentObj) {
	let result = await initMethods()();
	// console.log("initDataStore---result", result);
	if (result.exits && !isRefresh) {
		console.log("存在缓存，直接返回缓存数据", dataStore);
		return store.commit("xxy/setDataStore", dataStore);
	}
	// let pageTreeContent = store.getters['gw/getRealComponentsList'][0][1] || [];//主体内容的
	let requestData = [];
	console.log("componentObj",componentObj)
	if (componentObj) {
		requestData.push({
			componentName: componentObj.componentName,
			id: componentObj.id
		});

	} else {

		//第一步拿到所有的id
		let componentsList = store.getters['gw/getRealComponentsList'][0][0]
			.concat(store.getters['gw/getRealComponentsList'][0][1])
			.concat(store.getters['gw/getRealComponentsList'][0][2]);
		for (var i = 0; i < componentsList.length; i++) {
			requestData.push({
				componentName: componentsList[i].componentName,
				id: componentsList[i].id
			});
		}
	}
	console.log('requestData',requestData)
	requestData.forEach(item => {
		startQueryData(item)();
	});
	console.log('requestData22',requestData)
	console.log("任务队列", tasks);
	await Promise.all(tasks).then(() => {tasks = [];});
	console.log("数据请求完成并且构建完dataStore", dataStore);
    // sessionStorage.setItem("dataStore", JSON.stringify(dataStore));
    //存储缓存数据
    return saveMethods()();
}

function startQueryData(requestParams) {
	console.log("打印组件去请求数据--->", requestParams.componentName);
    let _methods = {
        default: () => {},
        HomeCarousel: () => tasks.push(queryBanner(requestParams.id, requestParams.componentName)),
        ProductItemNew: () => tasks.push(queryProductItemNew(requestParams.id, requestParams.componentName)),
        FeaturedGoodsNew: () => tasks.push(queryFeaturedGoodsNew(requestParams.id, requestParams.componentName)),
        FirstClassifyNew: () => tasks.push(queryfinalListNew(requestParams.id, requestParams.componentName)),
        NewZone: () => tasks.push(queryNewZone(requestParams.id, requestParams.componentName)),
        activitiesbanner: () => tasks.push(queryallBanner(requestParams.id, requestParams.componentName)),
        activitiesSlidePic: () => tasks.push(queryslidePic(requestParams.id, requestParams.componentName)),
        activitiesTwoPro: () => tasks.push(queryTwoPro(requestParams.id, requestParams.componentName)),
        activitiesNinePro: () => tasks.push(queryNinePro(requestParams.id, requestParams.componentName)),
        ActivitieCoupons2: () => tasks.push(queryCoupons2(requestParams.id, requestParams.componentName)),
		ActivitieCoupons: () => tasks.push(queryCoupons(requestParams.id, requestParams.componentName)),
		activitiesOnePro: () => tasks.push(queryOnePro(requestParams.id, requestParams.componentName)),
		activitiesThreePic: () => tasks.push(querythreePic(requestParams.id, requestParams.componentName)),
		PointMallCarousel: () => tasks.push(queryPointMallBanner(requestParams.id, requestParams.componentName)),
		GiftBuyCarousel:() => tasks.push(queryGiftBuyBanner(requestParams.id, requestParams.componentName)),
    };
    return _methods[requestParams.componentName] || _methods.default;
}
//轮播图片数据
function queryBanner(id, componentName) {
	let url = window.api.goods_host + window.api.home_ad;
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//积分商城里轮播图片数据
function queryPointMallBanner(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/integral';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}

function queryGiftBuyBanner(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/gift';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}

//菜单图标（新分类数据）
function queryProductItemNew(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/icon';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//促销活动专区(新的特色商品)
function queryFeaturedGoodsNew(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/pro_act';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//新人专区
function queryNewZone(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/newborn';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//新分类推荐数据
function queryfinalListNew(id, componentName) {
	let url = window.api.goods_host + "/resourceConfig/mobile/new_qc";
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			usePlatform: "wap",
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			console.log('打印打印打印',data,data.data)
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//顶部大海报数据
function queryallBanner(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/posters';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//可滑动图片
function queryslidePic(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/slide_pic';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//三张图片
function querythreePic(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/three_pic';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//一排两个商品
function queryTwoPro(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/two_pro';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id,
			usePlatform: "wap",
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//独个商品
function queryOnePro(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/one_pro';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id,
			usePlatform: "wap",
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//三列下滑组件
function queryNinePro(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/nine_pro';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id,
			usePlatform: "wap",
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//优惠券信息
function queryCoupons(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/act_coup';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id,
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}

function queryCoupons2(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/activities_pic_coupons';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id,
		},
	}
	return axios(options).then(data => {
		if(data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}

//动态改变模板数据
async function getDataStoreChange(id, componentName, data) {
	try {
		dataStore[componentName] = {
			...dataStore[componentName],
			[id]: data[0] ? data[0][id] : []
		}
		store.commit("xxy/setDataStore", dataStore);
	} catch (err) {
		console.log("填充数据报错", err);
	}
}
export default initData